<template>
    <div class="Layout" ref="Layout">
        <div class="LeftLayout" :style="{
            width: MoveBarLeft + 3 + 'px'
        }">
            <Tags />
            <EditorVue v-if="EditorViewStatus" />
        </div>
        <div class="RightLayout" :style="{
            width: LayoutWidth - MoveBarLeft - 3 + 'px'
        }">
            <PreviewVue />
        </div>
        <div class="MoveBar" :style="{
            left: MoveBarLeft + 'px'
        }" @mousedown="MouseDown"></div>
        <div v-if="MouseDownStatus" class="MoveMark" @mouseup="MouseupEvent"></div>
    </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { useMouse } from '@vueuse/core'
import EditorVue from './Editor.vue';
import Tags from './Tag.vue'
import PreviewVue from './Preview.vue';
import { CodeEditor } from './Store';

const Layout = ref();
const { x } = useMouse();
const MouseDownStatus = ref(false);
const MoveBarLeft = ref(0);
const LayoutWidth = ref(0);
const MouseDown = () => {
    MouseDownStatus.value = true;
}
const MouseupEvent = () => {
    MouseDownStatus.value = false;
}
onMounted(() => {
    LayoutWidth.value = Layout.value.clientWidth;
    MoveBarLeft.value = LayoutWidth.value / 2 - 3;
})
watchEffect(() => {
    if (MouseDownStatus.value) {
        var Left = x.value - 3;
        if (Left < 300) {
            MoveBarLeft.value = 300;
        } else if (Left > LayoutWidth.value - 300) {
            MoveBarLeft.value = LayoutWidth.value - 300;
        } else {
            MoveBarLeft.value = Left
        }
    };
});

onUnmounted(() => {
    CodeEditor.destroy();
})

const EditorViewStatus = ref(false);

const SetCode = (CodeMapping: Record<string, string>) => {
    EditorViewStatus.value = false;
    CodeEditor.destroy();
    for (const key in CodeMapping) {
        const element = CodeMapping[key];
        CodeEditor.AddFile(key, element, false);
    }
    nextTick(() => {
        EditorViewStatus.value = true;
    })
};

const GetCode = () => {
    return JSON.parse(JSON.stringify(CodeEditor.state));
}

defineExpose({
    SetCode,
    GetCode
})


</script>
<style lang="less" scoped>
.Layout {
    width: 100%;
    height: 100%;
    position: relative;
}

.MoveMark {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999999;
    cursor: col-resize;
}

.MoveBar {
    position: absolute;
    width: 6px;
    height: 100%;
    top: 0;
    cursor: col-resize;
    transition: background 0.3s;
}

.LeftLayout {
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    background-color: #111111;
}

.RightLayout {
    position: absolute;
    top: 0;
    right: 0;
    width: 50%;
    height: 100%;
    background-color: #111111;
}
</style>